Skip to content

feat: weather-aware outfit extras, footwear weight and sun/cold hat rule - #337

Open
thisloke wants to merge 9 commits into
Anyesh:mainfrom
thisloke:feat/weather-aware-outfits
Open

thisloke wants to merge 9 commits into
Anyesh:mainfrom
thisloke:feat/weather-aware-outfits

Conversation

@thisloke

@thisloke thisloke commented Nov 12, 2026 •

Copy link
Copy Markdown

Description

Three changes so suggestions follow the weather more closely.

1. "If it gets cooler / If it warms up"
Each suggested outfit can name one layer from the wardrobe to add if the weather turns (a mid or outer layer not in the outfit), and one layer in the outfit that can come off if it gets warmer. The cooler layer is offered for every outfit unless the day is clearly hot, so people always know how to cover up for a sudden change.

  • Prompt: two optional fields per outfit, if_cooler and if_warmer (item numbers or null), with rules.
  • Backend: validated in resolve_layer_extras() (in range, right role, not archived or excluded, cooler not in the outfit, warmer in the outfit and removable, outfit still complete without it); invalid picks are dropped. Stored as two nullable FKs on outfits (ON DELETE SET NULL, one migration) and returned in OutfitResponse as if_cooler / if_warmer item summaries. The cached-suggestion path goes through the same validation.
  • UI: OutfitWeatherExtras rows with thumbnails on the suggest card and the outfit page, in all 8 locales.

2. Footwear weight
All "all-season" shoes used to weigh the same, so a chunky pair could win on a warm day while knit or mesh shoes were available. footwear_weight() classifies footwear as light, medium or heavy from type, subtype, material, seasons and description keywords (documented constants). When warm, heavy shoes are penalised strongly and medium ones mildly if a light pair exists; when cold, light shoes are penalised mildly. Nothing is excluded. The weight is shown on each footwear line in the prompt, with a rule to match it to the weather.

3. Sun and cold hat
The prompt now gets the UV index (current and today's max, uv_index_max from Open-Meteo) and wind when relevant. The generic "hat" accessory is replaced by a rule: a cap or sun hat when UV is 6 or higher, a warm hat when it is cold or windy, only if it suits the outfit, never just to complete the look. The scorer never favours hats.

Type of Change

  • New feature (non-breaking change that adds functionality)

Checklist

  • I have read the CONTRIBUTING guide
  • My code follows the project's coding style
  • I have added tests that prove my fix/feature works
  • New and existing tests pass locally
  • My changes don't introduce new warnings or errors

Screenshots

Outfit page with the two rows (test wardrobe with placeholder images):

Weather extras

Testing

  • Backend: new tests/test_footwear_weight.py, tests/test_sun_and_cold_hat.py, tests/test_weather_extras.py (classification table, warm-day ranking, prompt contents, extras validation, persistence, API, SET NULL on item delete, migration up/down). Full suite passes locally except two utc timezone tests that fail the same way on main on macOS. tests/test_migration_wore_instead_names.py now inserts with SQL, because the ORM model has the new columns. ruff clean.
  • Frontend: tsc --noEmit, npm run lint, npm test, npm run i18n:check.
  • Real model run (Claude Sonnet via OpenRouter, 15-item test wardrobe, /outfits/suggest-options):
Weather Result
24°C, sunny (override) 2 of 3 outfits with the light canvas sneakers, the third with medium ones; a cooler layer on all three; no hat
12°C, feels 9°C, 40% rain (override) every outfit got both a layer to add and one to take off; closed shoes or boots in 2 of 3
Real weather, UV max 8.8 the cap appears in one outfit only, the t-shirt and shorts look

Test Environment

  • Local development

Additional Notes

Notification emails and ntfy messages do not mention the extras yet.

Summary by Sourcery

Make outfit suggestions adapt more closely to changing temperatures, footwear warmth, sun exposure, and wind.

New Features:

  • Add weather-aware cooler and warmer outfit layer recommendations, including validated persistence, API responses, cached suggestions, and localized UI display.
  • Use footwear warmth classifications and weather-sensitive scoring to improve shoe recommendations without excluding available footwear.
  • Provide UV and wind context for sun and cold hat guidance in outfit suggestions.

Enhancements:

  • Expose daily maximum UV data from the weather service and incorporate sun and wind changes into suggestion cache context.
  • Preserve enough layer candidates for weather extras in larger wardrobes.

Tests:

  • Add backend coverage for footwear classification and ranking, weather prompt behavior, extra validation and persistence, weather data caching, and migration behavior.
  • Add frontend coverage for localized weather-extra rendering and item links.

…at rule

The outfit prompt now carries the current and peak UV index (and strong wind),
and the generic hat mention is replaced by a rule: a cap or sun hat at UV 6+,
a warm hat when it is cold or windy, never a hat just to complete the look.
…pting

Classify shoes as light, medium or heavy from type, subtype, material, seasons
and ai_description keywords. On warm days heavy shoes are penalised strongly,
and medium ones mildly when a light pair exists; on cold days light shoes are
penalised mildly. The weight is listed on each footwear line of the prompt,
with a rule to match footwear weight to the weather.
The stylist may name one wardrobe layer to add if it gets cooler and one of the
outfit's own layers to take off if it warms up. Both are validated (in range,
available, right role, not already in the outfit / actually in it and still
complete without it) and stored as two nullable foreign keys on outfits
(ON DELETE SET NULL). They are returned in every outfit response and shown as
compact rows on the suggestion card and the outfit page.
@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Schema and migrations

Add indexed nullable foreign keys for cooler and warmer outfit extras, with deletion clearing the references.

  • backend/migrations/versions/b3d9f1a2c4e6_add_outfit_weather_extras.py L1-46

Data structures

Add outfit relationships and response fields for the two weather extras, and expose their summary shape to frontend consumers.

  • backend/app/api/outfits.py L127-147 (+5 small edits)
  • backend/app/models/outfit.py L96-110, L147-153
  • frontend/lib/types.ts L347-359, L378-379

Extend the weather data structure to carry the daily maximum UV index.

  • backend/app/services/weather_service.py L39-40, L59

API

Serialize weather extras in outfit responses while hiding unavailable, duplicated, or no-longer-valid references.

  • backend/app/api/outfits.py L369-404, L428-444, L504-505

Implementation

Validate AI-selected cooler and warmer layers, recheck availability before saving, and include UV and wind conditions in prompt and cache context.

  • backend/app/services/recommendation_service.py L106-229, L846-854, L1061-1069 (+10 small edits)

Classify footwear warmth, adjust weather scoring and small-wardrobe ordering, and preserve candidates for cooler-layer suggestions.

  • backend/app/services/item_scorer.py L103-235, L437-449, L561-579 (+6 small edits)

Fetch and populate the daily maximum UV value from weather-provider responses.

  • backend/app/services/weather_service.py L306-515 (4 small edits)

UI

Render linked weather-extra rows on suggestion cards and outfit detail pages, with localized labels in all supported locales.

  • frontend/app/dashboard/outfits/[id]/page.tsx L26, L155-156
  • frontend/app/dashboard/suggest/page.tsx L53, L371-372
  • frontend/components/shared/outfit-weather-extras.tsx L1-55
  • frontend/messages/de/outfits.json L173-177
  • frontend/messages/en/outfits.json L173-177
  • frontend/messages/fr/outfits.json L173-177
  • frontend/messages/it/outfits.json L173-177
  • frontend/messages/ja/outfits.json L173-177
  • frontend/messages/ko/outfits.json L173-177
  • frontend/messages/zh-CN/outfits.json L173-177
  • frontend/messages/zh-TW/outfits.json L173-177

Configuration

Revise the recommendation prompt with footwear, hat, sun, and weather-extra guidance and the corresponding JSON fields.

  • backend/app/prompts/recommendation.txt L64-72 (+3 small edits)

Tests

Cover footwear classification, weather-sensitive ranking, prompt weight labels, and hat scoring behavior.

  • backend/tests/test_footwear_weight.py L1-244
  • backend/tests/test_item_scorer.py L691-708

Check sun and wind prompt context, cache invalidation, and weather-data UV round trips.

  • backend/tests/test_sun_and_cold_hat.py L1-110

Verify extra selection validation, persistence, API responses, deletion behavior, and migration rollback.

  • backend/tests/test_migration_wore_instead_names.py L3-10, L26-53
  • backend/tests/test_recommendation_service.py L124-851 (5 small edits)
  • backend/tests/test_weather_extras.py L1-319

Test localized weather-extra rendering, conditional rows, fallback labels, and item links.

  • frontend/tests/outfit-weather-extras.test.tsx L1-88

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions github-actions Bot added javascript Pull requests that update javascript code python Pull requests that update python code labels Nov 12, 2026

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 9 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="backend/app/services/recommendation_service.py" line_range="1058" />
<code_context>
             condition=weather.condition,
             precipitation_chance=weather.precipitation_chance,
             temp_range_text=format_temp_range_text(weather),
+            weather_details_text=format_weather_details_text(weather),
             preferences_text=preferences_text,
             items_text=items_text,
</code_context>
<issue_to_address>
**Cached advice ignores changing sun and wind**

When UV or wind changes while the cache-context fields still match, `suggestion_context()` omits UV and wind, so `cached_suggestion_fits()` accepts the old response and returns hat or layer advice generated for different conditions; users see a stale suggestion.

Include UV and wind in the suggestion cache context.
</issue_to_address>

### Comment 2
<location path="backend/app/services/item_scorer.py" line_range="203-204" />
<code_context>
+    # Warmest and coolest reading to judge shoes against, feels-like included.
+    temp_range = scoring_temp_range(weather)
+    if temp_range is not None:
+        mid = (temp_range[0] + temp_range[1]) / 2
+        return mid, mid
+    return (
+        max(weather.temperature, weather.feels_like),
</code_context>
<issue_to_address>
**Footwear scoring ignores temperature extremes**

When a qualifying temperature range crosses a footwear threshold that its midpoint does not, or the current feels-like reading crosses a threshold the midpoint does not, `_footwear_reference_temps()` returns the range midpoint for both values, so `_footwear_weight_score()` misses the range endpoints and current feels-like conditions; users can get shoes suited to the wrong temperatures.

Use the relevant temperature-range endpoints and current weather readings when calculating footwear reference temperatures.
</issue_to_address>

### Comment 3
<location path="backend/app/services/recommendation_service.py" line_range="136" />
<code_context>
+        if value is None:
+            return None
+        picked = picked_item_ids([value], number_map)
+        if len(picked) != 1 or picked[0] not in item_type_map:
+            logger.debug(f"Dropping {key}={value!r}: not an available item")
+            return None
</code_context>
<issue_to_address>
**Unavailable extras break or pollute saved outfits**

When a candidate extra is archived or deleted after candidate loading but before the outfit is saved, `resolve_layer_extras()` trusts the stale `item_type_map` and accepts the extra; `_save_outfit()` then stores an archived item or fails its foreign-key flush for a deleted item, so the user gets an unavailable extra or a failed request.

Recheck each selected extra's current availability before saving and drop unavailable extras.

Also at `backend/app/models/outfit.py:100`.
</issue_to_address>

### Comment 4
<location path="backend/app/services/item_scorer.py" line_range="644" />
<code_context>
     # score_items leaves small wardrobes unscored, so filling a missing piece needs its own
     # ranking or it would fall back to database order. Most items tie on fit in mild
     # weather, so the least recently worn goes first to avoid adding the same piece every time.
+    light_available = has_light_footwear(items)
+
     def key(item: ClothingItem) -> tuple[float, date]:
</code_context>
<issue_to_address>
**Small wardrobes skip footwear weighting**

When the wardrobe has fewer than `MIN_ITEMS_FOR_SCORING` candidates, `score_items()` returns before reaching the new footwear-weight calculation, so light and heavy shoes keep their incoming order and recommendations miss the intended warm-weather weighting.

Apply footwear weighting before the small-wardrobe early return or score those candidates normally.

Also at `backend/app/services/item_scorer.py:501`.
</issue_to_address>

### Comment 5
<location path="backend/app/api/outfits.py" line_range="408-409" />
<code_context>
+    # The outfit's items can change after the AI named its extras (studio edits), so an extra
+    # that no longer fits is hidden rather than shown wrongly.
+    outfit_item_ids = {outfit_item.item_id for outfit_item in outfit.items}
+    if_cooler = outfit.if_cooler_item
+    if if_cooler is not None and if_cooler.id in outfit_item_ids:
+        if_cooler = None
+    if_warmer = outfit.if_warmer_item
</code_context>
<issue_to_address>
**Archived extras remain in outfit responses**

When a referenced extra is archived after its outfit is saved, `outfit_to_response()` checks whether an extra is in the outfit but not whether it remains ready and unarchived, so the API returns an unavailable item and the UI still offers it as a weather suggestion.

Omit extras that are no longer ready and unarchived when building the outfit response.

Also at `backend/app/api/outfits.py:474-475`.
</issue_to_address>

### Comment 6
<location path="backend/app/api/outfits.py" line_range="412-413" />
<code_context>
+    if if_cooler is not None and if_cooler.id in outfit_item_ids:
+        if_cooler = None
+    if_warmer = outfit.if_warmer_item
+    if if_warmer is not None and if_warmer.id not in outfit_item_ids:
+        if_warmer = None
+
     feedback_summary = None
</code_context>
<issue_to_address>
**Essential warmer layers appear removable**

When an outfit edit leaves the warmer item in the outfit but makes the outfit incomplete without it, `outfit_to_response()` checks whether the warmer item is present but not whether removing it leaves a complete outfit, so the API returns it as a removable extra and the user sees an invalid weather suggestion.

Validate that the outfit remains complete without the warmer item before returning it as an extra.
</issue_to_address>

### Comment 7
<location path="backend/app/services/recommendation_service.py" line_range="135" />
<code_context>
+        value = outfit_data.get(key)
+        if value is None:
+            return None
+        picked = picked_item_ids([value], number_map)
+        if len(picked) != 1 or picked[0] not in item_type_map:
+            logger.debug(f"Dropping {key}={value!r}: not an available item")
</code_context>
<issue_to_address>
**Available layers go unoffered**

When the wardrobe has more than 70 scored candidates and a fitting layer ranks below the prompt cutoff, `_format_items_for_prompt` numbers only the scored items, and `resolve_layer_extras.pick` can resolve only numbers in that map. A fitting layer omitted by the item limit therefore cannot be suggested, so the cooler extra is missing despite that layer being in the wardrobe.

Reserve suitable mid- and outer-layer candidates when applying the prompt item limit, or otherwise ensure the extras can reference eligible layers outside the top-ranked list.
</issue_to_address>

### Comment 8
<location path="backend/app/services/recommendation_service.py" line_range="137" />
<code_context>
+            return None
+        picked = picked_item_ids([value], number_map)
+        if len(picked) != 1 or picked[0] not in item_type_map:
+            logger.debug(f"Dropping {key}={value!r}: not an available item")
+            return None
+        return picked[0]
</code_context>
<issue_to_address>
**Invalid weather extras go unnoticed**

When the AI returns an invalid extra item number, or the cached item-number mapping is stale, `resolve_layer_extras.pick()` drops an unavailable or malformed AI item number and logs only at debug level, so a prompt or item-number mapping regression can remove the weather extras from suggestions without an operator-visible signal; users see the rows missing.

Emit a warning or increment a metric when an extra is dropped so persistent failures are visible in production.
</issue_to_address>

### Comment 9
<location path="backend/migrations/versions/b3d9f1a2c4e6_add_outfit_weather_extras.py" line_range="28" />
<code_context>
+
+def upgrade() -> None:
+    for column in ("if_cooler_item_id", "if_warmer_item_id"):
+        op.add_column("outfits", sa.Column(column, UUID(as_uuid=True), nullable=True))
+        op.create_foreign_key(
+            f"fk_outfits_{column}",
</code_context>
<issue_to_address>
**Item deletion scans outfits**

When a clothing item referenced by outfits is deleted, postgreSQL must find outfits referencing the deleted clothing item to apply `ON DELETE SET NULL`; without indexes on these new foreign-key columns, deleting an item scans the outfits table, adding work as outfit history grows.

Add indexes on both foreign-key columns in the migration and model.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 9 findings to address first, and the new footwear scoring and AI weather extras can produce different outfit choices, which are saved on outfit records and remain after a revert. The affected outfits and extra-item pointers are bounded and can be edited or deleted; reverting restores future recommendations but does not remove records already created.

Blocking findings: backend/app/services/recommendation_service.py:1058, backend/app/services/item_scorer.py:204, backend/app/services/recommendation_service.py:136, backend/app/services/item_scorer.py:644, backend/app/api/outfits.py:409, and 4 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread backend/app/services/item_scorer.py Resolved
Comment thread backend/app/services/item_scorer.py Resolved
Comment thread backend/app/api/outfits.py Resolved
Comment thread backend/app/api/outfits.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

javascript Pull requests that update javascript code python Pull requests that update python code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants